const os = require('os')
const chilchild_processd = require('child_process')
const fs = require('fs')
const http = require('http')

function unique_array(arr) {
  return arr.filter(function (item, index, arr) {
    //当前元素，在原始数组中的第一个索引==当前索引值，否则返回当前元素
    return arr.indexOf(item, 0) === index
  })
}

function parsePac(buf) {
  let proxy_list = []
  let proxy_reg = /PROXY\s+\d+\.\d+\.\d+\.\d+\:\d+/g
  let matchs = buf.match(proxy_reg)

  if (matchs) {
    for (var i = 0; i < matchs.length; i++) {
      let proxy_url = 'http://' + matchs[i].substring(5).trim()
      proxy_list.push(proxy_url)
    }
  }

  return proxy_list
}

function request_get(url) {
  if (url.search('//localhost')) {
    url = url.replace('//localhost', '//127.0.0.1')
  }
  return new Promise(function (resolve, reject) {
    http
      .get(url, (resp) => {
        let data = ''
        resp.on('data', (chunk) => {
          data += chunk
        })

        // The whole response has been received. Print out the result.
        resp.on('end', () => {
          resolve(data)
        })
      })
      .on('error', (err) => {
        console.log('Error: ' + err.message)
        reject(err)
      })
  })
}

async function getSystemProxy(my_platform) {
  if (!my_platform) {
    my_platform = os.platform()
  }

  let proxy_list = []
  if (my_platform === 'darwin') {
    let r = chilchild_processd.execSync('system_profiler SPNetworkDataType')
    let buf = r.toString()

    let start_pos = 0
    let end_pos = 0
    let sep_pos = 0
    let new_buf = ''

    while (true) {
      start_pos = buf.search('Proxies:')
      if (start_pos < 0) {
        break
      }
      new_buf = buf.substring(start_pos)
      end_pos = new_buf.search('Service Order:')
      if (end_pos < 0) {
        break
      }
      let raw_conf = {}
      raw = buf.substring(start_pos + 8, start_pos + end_pos).trim()
      raw_list = raw.split(/[\r|\n]+/)
      for (var i = 0; i < raw_list.length; i++) {
        raw_row = raw_list[i].trim()
        sep_pos = raw_row.search(':')
        let my_key = raw_row.substring(0, sep_pos).trim()
        let my_value = raw_row.substring(sep_pos + 1).trim()
        raw_conf[my_key] = my_value
      }

      if (raw_conf['Auto Configure Enabled'] == 'Yes' && raw_conf['Auto Configure URL']) {
        try {
          let fetch_buf = await request_get(raw_conf['Auto Configure URL'])

          let raw_proxy = parsePac(fetch_buf)
          if (raw_proxy) {
            for (var j = 0; j < raw_proxy.length; j++) {
              proxy_list.push(raw_proxy[j])
            }
          }
        } catch (e) {}
      } else if (raw_conf['HTTP Proxy Enabled'] == 'Yes' && raw_conf['HTTP Proxy Server']) {
        proxy_list.push(
          'http://' + raw_conf['HTTP Proxy Server'] + ':' + raw_conf['HTTP Proxy Port']
        )
      }

      buf = buf.substring(start_pos + end_pos)
    }
  } else if (my_platform === 'win32') {
    let buf = ''
    try {
      let r = chilchild_processd.execSync(
        'reg query "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"'
      )
      buf = r.toString()
    } catch (e) {
      var data = fs.readFileSync('window1.txt')
      buf = data.toString()
    }

    // var data = fs.readFileSync('window.txt');
    // let buf = data.toString();
    // ProxyEnable    REG_DWORD    0x1

    let start_pos = buf.search('ProxyEnable')
    if (start_pos > 0) {
      let new_buf = buf.substring(start_pos)
      let end_pos = new_buf.search('\n')
      let raw = buf.substring(start_pos, start_pos + end_pos).trim()
      let raw_arr = raw.split(/\s+/)
      let isProxy = parseInt(raw_arr[raw_arr.length - 1], 16)
      if (isProxy > 0) {
        //有代理继续运行
        start_pos = buf.search('ProxyServer')
        if (start_pos > 0) {
          new_buf = buf.substring(start_pos)
          end_pos = new_buf.search('\n')
          raw = buf.substring(start_pos, start_pos + end_pos).trim()
          raw_arr = raw.split(/\s+/)
          let server = raw_arr[raw_arr.length - 1]
          let proxy_url = 'http://' + server.trim()
          proxy_list.push(proxy_url)
        }
      }
    }

    if (proxy_list.length < 1) {
      //二次确实是否有代理文件
      start_pos = buf.search('AutoConfigURL')
      if (start_pos > 0) {
        let new_buf = buf.substring(start_pos)
        let end_pos = new_buf.search('\n')
        raw = buf.substring(start_pos, start_pos + end_pos).trim()
        raw_arr = raw.split(/\s+/)
        let pac_url = raw_arr[raw_arr.length - 1]
        if (/http/.test(pac_url)) {
          let fetch_buf = ''
          try {
            fetch_buf = await request_get(pac_url)
          } catch (e) {}

          let raw_proxy = parsePac(fetch_buf)
          if (raw_proxy) {
            for (var j = 0; j < raw_proxy.length; j++) {
              proxy_list.push(raw_proxy[j])
            }
          }
        }
      }
    }
  }

  if (proxy_list) {
    proxy_list = unique_array(proxy_list)
  }

  return proxy_list
}

module.exports = getSystemProxy
